﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using BaseText;
using Srvtools;

public partial class WorkTimeN_WorkTimeEvection : System.Web.UI.Page
{

    #region 系统

    private Srvtools.WebDataSet WMaster;
    private bool EditCancel;

    //private Srvtools.WebDataSet FlListId;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            EditCancel = false;

            if (Request["id"] != null)
            {
                InitializeComponent(true);
                FLWebNavigator1.Visible = true;

                  string FlowFlag = Request["FlowFlag"].ToString();
                 string EmployeeId = Request["EmpId"].ToString();
                 if (FlowFlag == "" && Convert.ToInt32("0" + EmployeeId) == Convert.ToInt32(Srvtools.CliUtils.fLoginUser))
                 {
                 }
                 else
                 {
                     object o = FLWebNavigator1.NavControls["Comment"];
                    // FLWebNavigator1.NavControls.Clear();
                     FLWebNavigator1.NavControls.Add(o);
                 }

                Master.DataSource = WMaster;
                WMaster.SetWhere("EvectionId=" + Request["id"].ToString());

                DataSet ds = WMaster.Execute("SELECT SYS_TODOLIST.LISTID FROM SYS_TODOLIST WHERE  SYS_TODOLIST.FORM_TABLE='WorkTime_Evection'" +
                    " and SYS_TODOLIST.FORM_KEYS='EvectionId' and  SYS_TODOLIST.FORM_PRESENTATION='EvectionId=" + Request["id"].ToString() + "'");
                if (ds != null && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
                {
                    ImageButton imb = new ImageButton();
                    imb.ImageUrl = "../image/uipics/Comment_C.gif";
                    imb.ID = "i";
                    imb.Attributes.Add("onclick", "window.open('../InnerPages/FlowComment.aspx?LISTID=" + ds.Tables[0].Rows[0][0].ToString()
                        + "&ATTACHMENTS=', '', 'resizable=yes,scrollbars=yes,width=645,height=400,top=100,left=200');return false");
                    FLWebNavigator1.Controls.Add(imb);
                }

                if (WMaster.RealDataSet != null && 
                    WMaster.RealDataSet.Tables.Count > 0 && 
                    WMaster.RealDataSet.Tables[0].Rows.Count > 0 && 
                    WMaster.RealDataSet.Tables[0].Rows[0] != null &&
                    WMaster.RealDataSet.Tables[0].Rows[0]["FlowFlag"].ToString().ToUpper().Trim() == "Z")
                {
                    EditCancel = true;
                }
            }
            else
            {
                InitializeComponent(false);
                Master.DataSource = WMaster;
            }

            MasterPage_MasterPage mpg = (MasterPage_MasterPage)this.Page.Master;
            mpg.HelpHref = "~/Help/WorkTime/员工出差流程.htm";
            mpg.PageName = "出差单";
            mpg.PicUrl = "";
            mpg.IntiBar();
        }
    }

    private void InitializeComponent(bool action)
    {
        System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WorkTimeN_WorkTimeEvection));
        this.WMaster = new Srvtools.WebDataSet();
        ((System.ComponentModel.ISupportInitialize)(this.WMaster)).BeginInit();
        // 
        // WMaster
        // 
        this.WMaster.Active = action;
        this.WMaster.AlwaysClose = true;
        this.WMaster.DeleteIncomplete = true;
        this.WMaster.Guid = null;
        this.WMaster.LastKeyValues = null;
        this.WMaster.Locale = new System.Globalization.CultureInfo("zh-CN");
        this.WMaster.PacketRecords = 100;
        this.WMaster.Position = -1;
        this.WMaster.RemoteName = "SWorkTime.WorkTime_Evection";
        this.WMaster.ServerModify = true;
        ((System.ComponentModel.ISupportInitialize)(this.WMaster)).EndInit();
    }

    #endregion

    #region 事件

    protected void WebFormView1_ItemInserting(object sender, FormViewInsertEventArgs e)
    {

        //int hours = this.GetHours(Convert.ToDateTime(startDate.Text), Convert.ToDateTime(endDate.Text));
        e.Values["EveHours"] = 0;

    }

    protected void WebFormView1_ItemUpdating(object sender, FormViewUpdateEventArgs e)
    {
        TextBox startDate = (TextBox)this.WebFormView1.FindControl("ZLTextBox1");
        TextBox endDate = (TextBox)this.WebFormView1.FindControl("ZLTextBox2");

        if (startDate == null || endDate == null)
            return;

        //int hours = this.GetHours(startDate.GetDateTime, endDate.GetDateTime);
        e.NewValues["EveHours"] = 0;
    }

    protected void btnHours_Click(object sender, EventArgs e)
    {
        ZLTextBox tbHours = (ZLTextBox)this.WebFormView1.FindControl("ZLTextBox3");
        TextBox startDate = (TextBox)this.WebFormView1.FindControl("ZLTextBox1");
        TextBox endDate = (TextBox)this.WebFormView1.FindControl("ZLTextBox2");
        if (tbHours == null || startDate == null || endDate == null)
            return;
        if (this.ValidateDate(Convert.ToDateTime(startDate.Text), Convert.ToDateTime(endDate.Text)) == false)
        {
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('终止日期必须大于起始日期\\r\\n或是\\r\\n请假时间不在工作时间之内');", true);
            return;
        }
        tbHours.Text = this.GetHours(Convert.ToDateTime(startDate.Text), Convert.ToDateTime(endDate.Text)).ToString();
    }

    #endregion

    #region 验证

    private DateTime start = DateTime.MinValue;
    private DateTime end = DateTime.MinValue;

    protected bool ValidateDateFrom(object value)
    {
        TextBox ZLTextBox1 = (TextBox)this.WebFormView1.FindControl("ZLTextBox1");
        TextBox ZLTextBox2 = (TextBox)this.WebFormView1.FindControl("ZLTextBox2");
        DateTime st = DateTime.Parse(ZLTextBox1.Text);
        DateTime et = DateTime.Parse(ZLTextBox2.Text);
        if (st.CompareTo(et) <= 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    protected bool ValidateDateTo(object value)
    {
        return true;
        end = DateTime.Parse(value.ToString());
        ZLTextBox ZLTextBox1 = (ZLTextBox)this.WebFormView1.FindControl("ZLTextBox1");
        ZLTextBox ZLTextBox2 = (ZLTextBox)this.WebFormView1.FindControl("ZLTextBox2");
        DateTime st = DateTime.Parse(ZLTextBox1.textValue);
        DateTime et = DateTime.Parse(ZLTextBox1.textValue);
        if (st.CompareTo(et) >= 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    private bool ValidateDate(DateTime start, DateTime end)
    {
        if (start.CompareTo(end) >= 0)
        {
            return true;
        }
        else
        {
            return false;
        }

        if (start != DateTime.MinValue && end != DateTime.MinValue)
        {
            int sHour = start.Hour;
            int sMinute = start.Minute;
            int eHour = end.Hour;
            int eMinute = end.Minute;

            if (sHour < 8 || sHour == 8 && sMinute < 30 || sHour > 17 || eHour < 8 || eHour == 8 && eMinute < 30 || eHour > 17)
            {
                return false;
            }

            if (start.CompareTo(end) >= 0)
            {
                return false;
            }
        }
        return true;
    }

    #endregion

    #region 自定义方法

    private int GetHours(DateTime stDate, DateTime end)
    {
        return 0;

        int counHour = 0;

        int sYear = stDate.Year;
        int sMonth = stDate.Month;
        int sDay = stDate.Day;
        int sHour = stDate.Hour;

        int eYear = end.Year;
        int eMonth = end.Month;
        int eDay = end.Day;
        int eHour = end.Hour;

        if (sYear == eYear && sMonth == eMonth && sDay == eDay)
        {
            if (sHour >= 12 || eHour <= 12)
            {
                counHour += 4;
            }
            else
            {
                counHour += 8;
            }
        }
        else
        {
            TimeSpan ts = end - stDate;
            if (ts.Days > 1)
            {
                counHour += (ts.Days - 1) * 8;
            }
            if (sHour >= 12)
                counHour += 4;
            else
                counHour += 8;
            if (eHour <= 12)
                counHour += 4;
            else
                counHour += 8;
        }
        return counHour;
    }

    protected bool IsDepVisible(string dep)
    {
        return dep != string.Empty;
    }



    #endregion

    #region 默认值绑定
    object[] oDiff = null;

    protected object GetDateTo()
    {
        //return (oDiff != null ? (Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + oDiff[0].ToString()).AddHours(-1)).ToString() : "");
        return (oDiff != null ? (Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + oDiff[1].ToString())).ToString() : "");
    }

    protected object GetDateFrom()
    {
        return (oDiff != null ? (Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + oDiff[0].ToString())).ToString() : "");
        //return (oDiff != null ? (Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + oDiff[1].ToString()).AddHours(1)).ToString() : "");
    }


    protected object GetEmployeeId()
    {
        String str = Srvtools.CliUtils.GetValue("_UserCode")[1].ToString();
        str = int.Parse(str).ToString();
        return str;
    }

    #endregion


    protected void WebFormView1_DataBound(object sender, EventArgs e)
    {
        if (WebFormView1.CurrentMode == FormViewMode.Insert || WebFormView1.CurrentMode == FormViewMode.Edit)
        {
            if (Request.Params["MS"] != null)
            {
                WebRefVal tbEmployee = (WebRefVal)this.WebFormView1.FindControl("WebRefVal1");
                if (tbEmployee != null)
                    tbEmployee.ReadOnly = false;
            }
            else
            {
                WebRefVal tbEmployee = (WebRefVal)this.WebFormView1.FindControl("WebRefVal1");
                if (tbEmployee != null)
                    tbEmployee.ReadOnly = true;
            }
        }

        if (WebFormView1.CurrentMode == FormViewMode.Insert)
        {
            //如果非新增，允许修改取消单选框
            CheckBox ckb = (CheckBox)this.WebFormView1.FindControl("ckbCancel");

            ckb.Enabled = false;
        }

        if (EditCancel)
        {
            dvLink.Visible = true;
            CheckBox ckb = (CheckBox)this.WebFormView1.FindControl("ckbCancel");
            ckb.Enabled = true;
            TextBox txt = (TextBox)this.WebFormView1.FindControl("txtMemo");
            txt.Enabled = true;
            txt.ReadOnly = false;
        }
        else
        {
            dvLink.Visible = false;
        }
    }

    protected void FLWebNavigator1_Command(object sender, CommandEventArgs e)
    {
        if (e.CommandName == "cmdAdd")
        {
            object[] myRet = CliUtils.CallMethod("SWorkTime", "GetWorkOnType", new object[1] { "WorkTime_WorkOnTypeGroup.EmployeeId=" + Convert.ToInt32(Srvtools.CliUtils.GetValue("_UserCode")[1].ToString()) });

            switch (myRet[1].ToString())
            {
                case "N":
                case "S":
                    oDiff = new object[] { ((DataSet)myRet[2]).Tables[0].Rows[0]["ect"].ToString(), ((DataSet)myRet[2]).Tables[0].Rows[0]["st"].ToString() };
                    break;
                default:
                    oDiff = new object[] { "08:30", "17:30" };
                    break;
            }
        }
        else if (e.CommandName == "cmdApply")
        {
            if (IsPostBack == true)
            {
                if (Request["id"] != null)
                {
                    //Master.Reload();
                    Master.SetWhere("EvectionId=" + Request["id"].ToString());
                }
                else
                {
                    //Master.Reload();
                }
            }
        }
    }

    protected void Master_ApplyError(object sender, ApplyErrorEventArgs e)
    {
        Response.Write(e);
    }

    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        CheckBox ckb = (CheckBox)this.WebFormView1.FindControl("ckbCancel");
        TextBox txt = (TextBox)this.WebFormView1.FindControl("txtMemo");
        InitializeComponent(true);
        WMaster.Execute("UPDATE WorkTime_Evection Set Cancel ='" + ckb.Checked + "',Memo = '" + txt.Text.Replace("'", "''") + "' Where EvectionId = " + Request["id"].ToString());

        Response.Redirect(Request.Url.ToString());
    }
}
